package com.qf.sms.service.impl;

import com.qf.dto.sms.SmsDTO;
import com.qf.sms.dao.SmsHisDao;
import com.qf.sms.exception.SmsSendException;
import com.qf.sms.model.SmsHis;
import com.qf.sms.model.SmsHisExample;
import com.qf.sms.service.SmsService;
import com.qf.sms.util.TencentSmsUtil;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 短信业务逻辑的实现类
 * @version v1.0.0
 * @Description:
 * @author: 姜红凯
 * @date: 2022.04.10
 * @since 1.0
 */
@Service
public class SmsServiceImpl implements SmsService {


    public static final int MAX_SMS_TIME=1000*60*5;

    @Resource
    private SmsHisDao smsHisDao;

    @Transactional(rollbackFor = SmsSendException.class)
    @Override
    public int sendSms(String phoneNo, String code, Integer typeId) throws SmsSendException {
           //保存到历史表里
           SmsHis smsHis=new SmsHis();
           smsHis.setTime(System.currentTimeMillis());
           smsHis.setServiceTypeId(typeId);
           smsHis.setPhoneNo(phoneNo);
           smsHis.setCode(code);
           //可不可能短信历史添加失败？
           int count =smsHisDao.insertSelective(smsHis);
           if (count>0){
               boolean result=TencentSmsUtil.send(phoneNo,code);
               if (result){
                   return 1;
               }else {
                   throw new SmsSendException(SmsSendException.TENCENT_SMS);
               }
           }
           return 0;

    }

    @Override
    public int checkSms(String phoneNo, String code, Integer typeId) {
        //查数据
        SmsHisExample example=new SmsHisExample();
        SmsHisExample.Criteria criteria = example.createCriteria();
        criteria.andPhoneNoEqualTo(phoneNo);
        criteria.andServiceTypeIdEqualTo(typeId);
        //设置查询的排序方式
        example.setOrderByClause("`time` desc");
        List<SmsHis> smsHis = smsHisDao.selectByExample(example);
        if(smsHis!=null&&smsHis.size()>0){
            //取typeId这个服务类型，给phoneNo这个手机号发送的最后一条短信。
            SmsHis sms=smsHis.get(0);
            if(sms.getCode().equals(code)){
                //判断时间
                if(System.currentTimeMillis()-sms.getTime()<=MAX_SMS_TIME){
                    //正常，验证通过
                    return 0;
                }else{
                    //短信已经超时
                    return 1;
                }
            }else{
                //短信验证码的内容不相同
                return 2;
            }
        }
        //短信根本就没发，校验短信一定是内容错误
        return 2;
    }
}
